iT邦幫忙

2024 iThome 鐵人賽

DAY 14
0
JavaScript

Javascript網頁程式管理系統系列 第 14

day 14 javascript航班飛機追蹤網頁程式管理系統

  • 分享至 

  • xImage
  •  

今天是第十四天我們可以寫一個javascript航班飛機追蹤網頁程式管理系統,以下是程式碼

1. HTML 結構

這是網頁的結構,包含輸入框、按鈕和顯示航班資訊的區域。

<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>航班追蹤系統</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <h1>航班追蹤系統</h1>

        <div class="search-box">
            <input type="text" id="flightNumber" placeholder="輸入航班號碼">
            <button onclick="getFlightInfo()">搜尋航班</button>
        </div>

        <div id="flightInfo" class="flight-info">
            <!-- 航班資訊將顯示在這裡 -->
        </div>
    </div>

    <script src="app.js"></script>
</body>
</html>

2. CSS (style.css)

簡單的樣式設計來美化網頁。

body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f9;
    margin: 0;
    padding: 0;
    text-align: center;
}

.container {
    margin-top: 50px;
}

.search-box {
    margin-bottom: 20px;
}

input[type="text"] {
    padding: 10px;
    width: 250px;
    border: 1px solid #ccc;
    border-radius: 5px;
}

button {
    padding: 10px 20px;
    background-color: #28a745;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

button:hover {
    background-color: #218838;
}

.flight-info {
    margin-top: 20px;
    background-color: #fff;
    padding: 20px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    display: none;
}

3. JavaScript (app.js)

JavaScript 處理航班查詢並顯示結果。如果您使用外部 API,如 OpenSky Network,這裡需要調用 API 並顯示航班資訊。

async function getFlightInfo() {
    const flightNumber = document.getElementById('flightNumber').value;

    if (flightNumber.trim() === '') {
        alert('請輸入航班號碼');
        return;
    }

    try {
        // 使用一個假設的 API 呼叫獲取航班資料
        const response = await fetch(`https://api.example.com/flight/${flightNumber}`);
        const flightData = await response.json();

        displayFlightInfo(flightData);
    } catch (error) {
        alert('無法獲取航班資訊,請稍後再試。');
        console.error('Error fetching flight data:', error);
    }
}

function displayFlightInfo(flightData) {
    const flightInfoDiv = document.getElementById('flightInfo');
    flightInfoDiv.style.display = 'block';

    flightInfoDiv.innerHTML = `
        <h3>航班資訊</h3>
        <p><strong>航班號碼:</strong> ${flightData.flightNumber}</p>
        <p><strong>航空公司:</strong> ${flightData.airline}</p>
        <p><strong>出發機場:</strong> ${flightData.departureAirport}</p>
        <p><strong>目的地機場:</strong> ${flightData.arrivalAirport}</p>
        <p><strong>飛行狀態:</strong> ${flightData.status}</p>
    `;
}

4. API 整合

要實現實時的航班追蹤功能,您需要使用像 OpenSky NetworkFlightAware 等提供實時航班資料的 API。可以從這些 API 提供者那裡註冊並獲取 API Key,然後在 fetch() 方法中使用 API Endpoint 進行資料請求。

範例 API 整合(OpenSky Network)

async function getFlightInfo() {
    const flightNumber = document.getElementById('flightNumber').value;

    if (flightNumber.trim() === '') {
        alert('請輸入航班號碼');
        return;
    }

    try {
        // 使用 OpenSky Network API 進行查詢
        const response = await fetch(`https://opensky-network.org/api/states/all`);
        const flightData = await response.json();

        // 處理航班資料
        const filteredFlight = flightData.states.find(flight => flight[1] === flightNumber);
        
        if (filteredFlight) {
            const flightInfo = {
                flightNumber: flightNumber,
                airline: filteredFlight[2],
                departureAirport: filteredFlight[11],
                arrivalAirport: filteredFlight[13],
                status: '飛行中' // 假設狀態
            };
            displayFlightInfo(flightInfo);
        } else {
            alert('找不到該航班資訊');
        }
    } catch (error) {
        alert('無法獲取航班資訊,請稍後再試。');
        console.error('Error fetching flight data:', error);
    }
}

5. 儲存及擴展功能

除了基本的航班查詢,您可以擴展系統,提供以下功能:

  • 儲存常用的航班查詢歷史
  • 使用地圖顯示航班的實時位置(可以整合 Google Maps 或其他地圖 API)
  • 提供自動更新功能,定時更新航班狀態

我會以javascript做主要程式解說

async function getFlightInfo() {
    const flightNumber = document.getElementById('flightNumber').value;

    if (flightNumber.trim() === '') {
        alert('請輸入航班號碼');
        return;
    }

    try {
        // 使用一個假設的 API 呼叫獲取航班資料
        const response = await fetch(`https://api.example.com/flight/${flightNumber}`);
        const flightData = await response.json();

        displayFlightInfo(flightData);
    } catch (error) {
        alert('無法獲取航班資訊,請稍後再試。');
        console.error('Error fetching flight data:', error);
    }
}

function displayFlightInfo(flightData) {
    const flightInfoDiv = document.getElementById('flightInfo');
    flightInfoDiv.style.display = 'block';

    flightInfoDiv.innerHTML = `
        <h3>航班資訊</h3>
        <p><strong>航班號碼:</strong> ${flightData.flightNumber}</p>
        <p><strong>航空公司:</strong> ${flightData.airline}</p>
        <p><strong>出發機場:</strong> ${flightData.departureAirport}</p>
        <p><strong>目的地機場:</strong> ${flightData.arrivalAirport}</p>
        <p><strong>飛行狀態:</strong> ${flightData.status}</p>
    `;
}

1. getFlightInfo() 函式

這個函式是主要的入口點,當使用者點擊「搜尋航班」按鈕時,會呼叫這個函式。

async function getFlightInfo() {
    // ...
}

步驟解析:

  • 取得航班號碼:

    const flightNumber = document.getElementById('flightNumber').value;
    
    • 使用 document.getElementById() 獲取輸入框(<input> 元素)的值,也就是使用者輸入的航班號碼。
    • flightNumber 變數現在包含了使用者輸入的航班號碼。
  • 檢查航班號碼是否為空:

    if (flightNumber.trim() === '') {
        alert('請輸入航班號碼');
        return;
    }
    
    • 使用 trim() 方法移除字串前後的空白。
    • 如果 flightNumber 為空字串,則提示使用者「請輸入航班號碼」,並使用 return 終止函式執行。
  • 嘗試獲取航班資料:

    try {
        // ...
    } catch (error) {
        // ...
    }
    
    • 使用 try...catch 塊來處理可能發生的錯誤,特別是在進行網路請求時。
  • 發送 API 請求:

    const response = await fetch(`https://api.example.com/flight/${flightNumber}`);
    
    • 使用 fetch() 方法發送 HTTP 請求到指定的 API 端點。
    • 這裡使用了模板字串(Template String)將 flightNumber 插入到 URL 中。
    • await 關鍵字使函式等待 fetch() 完成後再繼續執行,需要注意這個函式前面有 async 關鍵字。
  • 解析回應資料:

    const flightData = await response.json();
    
    • 使用 response.json() 將回應的 JSON 資料解析為 JavaScript 物件。
    • 同樣使用 await 等待解析完成。
  • 顯示航班資訊:

    displayFlightInfo(flightData);
    
    • 呼叫 displayFlightInfo() 函式,並將獲取的 flightData 傳遞給它,用於在頁面上顯示航班資訊。
  • 錯誤處理:

    } catch (error) {
        alert('無法獲取航班資訊,請稍後再試。');
        console.error('Error fetching flight data:', error);
    }
    
    • 如果在 try 塊中發生錯誤(例如網路問題、伺服器錯誤等),會進入 catch 塊。
    • 使用 alert() 提示使用者「無法獲取航班資訊,請稍後再試。」。
    • 使用 console.error() 將錯誤資訊輸出到瀏覽器的控制台,方便開發者進行除錯。

2. displayFlightInfo(flightData) 函式

這個函式負責將獲取的航班資料顯示在網頁上。

function displayFlightInfo(flightData) {
    // ...
}

步驟解析:

  • 取得顯示航班資訊的容器:

    const flightInfoDiv = document.getElementById('flightInfo');
    
    • 使用 document.getElementById() 獲取要顯示航班資訊的 <div> 元素。
  • 顯示容器:

    flightInfoDiv.style.display = 'block';
    
    • 將容器的 CSS display 屬性設為 'block',確保容器是可見的。
    • 在初始的 CSS 中,可能將該容器設為 display: none;,隱藏起來,只有在有資料時才顯示。
  • 插入航班資訊:

    flightInfoDiv.innerHTML = `
        <h3>航班資訊</h3>
        <p><strong>航班號碼:</strong> ${flightData.flightNumber}</p>
        <p><strong>航空公司:</strong> ${flightData.airline}</p>
        <p><strong>出發機場:</strong> ${flightData.departureAirport}</p>
        <p><strong>目的地機場:</strong> ${flightData.arrivalAirport}</p>
        <p><strong>飛行狀態:</strong> ${flightData.status}</p>
    `;
    
    • 使用模板字串(Template String)將航班資訊動態插入到 HTML 中。
    • ${flightData.flightNumber} 等表示法會被替換為 flightData 物件中的相應屬性值。
    • 將組合好的 HTML 字串賦值給 flightInfoDiv.innerHTML,這會更新容器中的內容。

補充說明

  • asyncawait

    • async 關鍵字用於宣告異步函式,允許在函式內使用 await
    • await 用於等待一個 Promise 完成,只有在 async 函式中才能使用。
    • 這種用法可以讓異步程式碼看起來更像同步程式碼,方便閱讀和維護。
  • 使用假設的 API:

    • 在程式碼中,fetch() 呼叫的 URL 是 https://api.example.com/flight/${flightNumber},這是一個佔位符。
    • 在實際應用中,您需要替換為真實的 API 端點,並可能需要處理 API 金鑰、認證等問題。
  • 錯誤處理:

    • 良好的錯誤處理可以提高使用者體驗,並幫助開發者快速定位問題。
    • 使用 try...catch 可以捕獲異步操作中的錯誤。
  • DOM 操作:

    • 使用 document.getElementById()element.styleelement.innerHTML 等方式操作 DOM,更新網頁內容。
    • 這種方式適用於簡單的應用,對於更複雜的情況,可以考慮使用框架如 React、Vue 等。

實際應用中的調整

  • 整合真實的航班資料 API:

    • 選擇一個提供航班資料的 API,例如 OpenSky Network、FlightAware、AviationStack 等。
    • 註冊並獲取 API 金鑰(如果需要)。
    • 根據 API 文件,調整 fetch() 的 URL、請求方法、請求頭和參數。
  • 處理跨域問題:

    • 如果遇到跨域(CORS)問題,需要確保 API 支援跨域請求,或者使用後端代理。
  • 改善使用者體驗:

    • 在發送請求時顯示載入中的提示,防止使用者誤以為系統無回應。
    • 處理更多的錯誤狀況,如網路連線問題、API 回傳錯誤訊息等。
  • 安全性考量:

    • 如果需要在客戶端儲存或使用敏感資訊(如 API 金鑰),應避免將其直接暴露在前端程式碼中。
    • 可以考慮使用後端服務來處理 API 請求,前端與後端通訊。

總結

這段 JavaScript 程式碼的主要功能是:

  • 取得使用者輸入的航班號碼。
  • 驗證輸入是否有效。
  • 向航班資料 API 發送請求,獲取相應的航班資訊。
  • 將獲取的資訊動態地顯示在網頁上。

上一篇
day 13 javascript比價網站網頁程式管理系統
下一篇
day 15 javascript餐廳推薦網頁程式管理系統
系列文
Javascript網頁程式管理系統25
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言